addEvent("onload", init);
addEvent("onresize", checkOrientation);

var screenmode = 0;

function init(){
    try {
        var myStyleTweaks = new StyleTweaker();
        myStyleTweaks.add("Series60/5.0", "styles/tweaks/S605th.css");
        myStyleTweaks.add("Series60/3.2", "styles/tweaks/S603rdFP2.css");
        myStyleTweaks.tweak();
        
        initService();
        initFilterDates();
        list();
    } 
    catch (e) {
        alert(e.toString());
    }
}

function checkOrientation(){
    try {
        var width = parseInt(screen.width);
        var height = parseInt(screen.height);
        
        //var landscapeTweaker = new StyleTweaker();
        // Landscape tweaks for template styles not available in templates?
        //landscapeTweaker.add("Series60/5.0", "../resources/styles/tweaks/S605thLandscape.css");
        
        if (width > height) {
        
            // if already in landscape mode, return
            if (screenmode == 1) 
                return;
            screenmode = 1;
            // landscapeTweaker.tweak();
        }
        else {
            // if already in portrait mode, return
            if (screenmode == 0) 
                return;
            screenmode = 0;
            //        landscapeTweaker.untweak();
        }
    } 
    catch (e) {
        alert(e.toString());
    }
}

/*
 * Shows new entry form
 */
function newEntry(){
    document.getElementById("f2").reset();
    adjustForm("Meeting");
    initNewEventDates();
    document.getElementById("header").innerHTML = "New Event";
    document.getElementById("eventListContainer").style.display = "none";
    document.getElementById("newEventFormContainer").style.display = "block";
}

/*
 * Shows calendar events screen
 */
function showEventList(){
    document.getElementById("header").innerHTML = "Calendar Events";
    document.getElementById("eventListContainer").style.display = "block";
    document.getElementById("newEventFormContainer").style.display = "none";
}


/*
 * Shows or hides alarm date and time fields
 */
function showHideAlarm(o){
    if (o.value == "on" && o.checked) {
        showElement("alarmContainer", true);
    }
    else 
        showElement("alarmContainer", false);
}

/*
 * shows or hides new entry form UI element and its label
 * eid - element id
 * f - flag: true/false, true-show, false-hide
 */
function showElement(eid, f){
    document.getElementById(eid).style.display = (f ? "" : "none");
    document.getElementById(eid + "L").style.display = (f ? "" : "none");
}

/*
 * Adjusts new entry form depending on type
 * type - entry type: "Meeting", "ToDo", "Anniversary", "DayEvent" 
 * NOTE: "Reminder" is not implemented
 */
function adjustForm(type){
    switch (type) {
        case "Meeting":
            showElement("locationContainer", true);
            showElement("startDateContainer", true);
            showElement("startTimeContainer", true);
            showElement("endDateContainer", true);
            showElement("endTimeContainer", true);
            break;
        case "DayEvent":
            showElement("locationContainer", false);
            showElement("startDateContainer", true);
            showElement("startTimeContainer", false);
            showElement("endDateContainer", true);
            showElement("endTimeContainer", false);
            break;
        case "ToDo":
            showElement("locationContainer", false);
            showElement("startDateContainer", false);
            showElement("startTimeContainer", false);
            showElement("endDateContainer", true);
            showElement("endTimeContainer", false);
            break;
        case "Anniversary":
            showElement("locationContainer", false);
            showElement("startDateContainer", true);
            showElement("startTimeContainer", false);
            showElement("endDateContainer", false);
            showElement("endTimeContainer", false);
            break;
    }
    document.getElementById("alarmOff").checked = true;
    showElement("alarmContainer", false);
}

/*
 * Initializes calendar entry filter dates
 * sets start date to today, end day - one week forward
 */
function initFilterDates(){
    var today = new Date();
    document.getElementById("filterStartDate").value = formatDate(today);
    today.setDate(today.getDate() + 7);
    document.getElementById("filterEndDate").value = formatDate(today);
}

/*
 * Initializes new event form dates.
 */
function initNewEventDates(){
    var today = new Date();
    today.setMinutes(0);
    today.setHours(today.getHours() + 1);
    document.getElementById("startDate").value = formatDate(today);
    document.getElementById("startTime").value = formatTime(today);
    today.setMinutes(today.getMinutes() - 15);
    document.getElementById("alarmDate").value = formatDate(today);
    document.getElementById("alarmTime").value = formatTime(today);
    today.setMinutes(today.getMinutes() + 15);
    today.setHours(today.getHours() + 1);
    document.getElementById("endDate").value = formatDate(today);
    document.getElementById("endTime").value = formatTime(today);
}

/*
 * formats JS Date object to format: dd/MM/yyyy
 * date - date object to be formated
 */
function formatDate(date){
    var separator = "/";
    return preformatNumber(date.getDate()) + separator + preformatNumber((date.getMonth() + 1)) + separator + date.getFullYear();
}

/*
 * formats string date to format: dd/MM/yyyy
 * date - string representation of JS Date object to be formated
 */
function formatDateString(date){
    if (date == null) 
        return "";
    return formatDate(new Date(date));
}

/*
 * formats time of JS Date object to format: HH:mm
 * date - date object to be formated
 */
function formatTime(date){
    var separator = ":";
    return preformatNumber(date.getHours()) + separator + preformatNumber(date.getMinutes());
    
}

/*
 * Formats JS Date object to format: 'dd/MM/yyyy hh:mm'
 * date - date object to be formated
 */
function formatDateTime(date){
    var separator = "/";
    return preformatNumber(date.getDate()) + separator + preformatNumber((date.getMonth() + 1)) + separator + date.getFullYear() + " " + preformatNumber(date.getHours()) + ":" + preformatNumber(date.getMinutes());
    
}

/*
 * Adds extra '0' in front of number if it is < 10
 */
function preformatNumber(n){
    return n < 10 ? "0" + n : n;
}

/*
 * Parses string to JS Date. Accepts only dd/MM/yyyy format.
 * returns JS Date object
 */
function parseDate(date){
    var d = date.split("/");
    if (d[0] < 1 || d[0] > 31 || d[1] < 1 || d[1] > 12) 
        throw "Invalid date.\nCorrect date format \"dd/MM/yyyy\"";
    
    return new Date(d[2], parseInt(d[1]) - 1, d[0]);
}

/*
 * Parses string to JS Date with time. Accepts only dd/MM/yyyy HH:mm format.
 * returns JS Date object
 */
function parseDateTime(date, time){
    var d = date.split("/");
    var t = time.split(":");
    if (d[0] < 1 || d[0] > 31 || d[1] < 1 || d[1] > 12 || t[0] > 23 || t[1] > 59) 
        throw "Invalid date.\nCorrect date format \"dd/MM/yyyy HH:mm\"";
    
    return (new Date(d[2], parseInt(d[1]) - 1, d[0], t[0], t[1]));
    
}

/*
 * Sets all calendar events checkboxes to specified status
 * checked - status to be set: true or false
 */
function chALL(checked){
	var items = document.f1.ch;
	if(items==null) return;
	if(items.length){
		for (var i = 0; i < items.length; i++) {
			items[i].checked = checked;
		}
	}else
		items.checked = checked;
}

/*
 * Sets 'all' checkbox to 'checked' status if all calendar events checkboxes are checked 
 */
function checkMain(){
	var items = document.f1.ch;
	if(items==null) return;
	var checked = true;
	if (items.length) {
		for (var i = 0; i < items.length; i++) {
			checked = checked && items[i].checked;
		}
	}else
		checked = items.checked;
	document.f1.chAll.checked = checked;
}

/*
 * Deletes all selected calendar events and refreshes events list
 * deleteEvent(id) is defined in platformservices_20_specific.js
 */
function deleteEvents(){
    if (!confirm('Delete selected event(s)?')) 
        return;
    
    var events = document.f1.ch;
	if (events == null) return;
    if (events.length) {
		for (var i = 0; i < events.length; i++) {
			if (events[i].checked) {
				deleteEvent(events[i].value);
			}
		}
	}else
		deleteEvent(events.value);
		
    list();
}



/*
 * OnChange handler for filter form elements
 * lists calendar entries matching criterias in filter form
 */
function list(){
    listEntries(document.getElementById("filterType").options[document.getElementById("filterType").selectedIndex].value, document.getElementById("filterStartDate").value, document.getElementById("filterEndDate").value);
}

/*
 * OnClick handler for save button
 * adds new entry to calendar 
 */
function add(){
    var start = null, end = null, alarm = null, location = null;
    try {
        var type = document.getElementById("type").options[document.getElementById("type").selectedIndex].value;
        
        switch (type) {
            case "Meeting":
                start = parseDateTime(document.getElementById("startDate").value, document.getElementById("startTime").value);
                end = parseDateTime(document.getElementById("endDate").value, document.getElementById("endTime").value);
                location = document.getElementById("location").value;
                break;
            case "DayEvent":
                start = parseDate(document.getElementById("startDate").value);
                end = parseDate(document.getElementById("endDate").value);
				start.setHours(23);	start.setMinutes(59);
				end.setHours(23);	end.setMinutes(59);
                break;
            case "ToDo":
                end = parseDate(document.getElementById("endDate").value);
                break;
            case "Anniversary":
                start = parseDate(document.getElementById("startDate").value);
				start.setHours(23);	start.setMinutes(59);
                break;
        }
        
        var summary = document.getElementById("description").value;
        if (document.getElementById("alarmOn").checked) 
            alarm = parseDateTime(document.getElementById("alarmDate").value, document.getElementById("alarmTime").value);
        
        addEntry(type, start, end, alarm, summary, location);
        list();
        showEventList();
    } 
    catch (e) {
        alert(e.toString());
    }
}

/*
 *  Builds one row for calendar entries list HTML table based on calendar entry data.
 *  entry - calendar entry to be shown
 */
function showEntry(entry){

    var begin = null;
    var end = null;
    var txt = "<tr>";
    try {
        txt += "<td width='5'><input type='checkbox' onclick='checkMain()' name='ch' value='" + entry["id"] + "'/></td>";
        txt += "<td width='5'>" + entry["type"].substring(0, 2) + "</td>";
        txt += "<td>";
        if (entry.time.begin) 
            begin = new Date(entry.time.begin);
        if (entry.time.end) 
            end = new Date(entry.time.end);
        
        if (entry["type"] == "Meeting") {
            if (begin.getDate() == end.getDate()) {
                txt += formatTime(begin) + " - " + formatTime(end) + " " + formatDateString(begin);
            }
            else {
                txt += formatDateTime(begin);
                txt += " - " + formatDateTime(end);
            }
        }
        else {
            if (begin != null) {
                txt += formatDateString(entry.time.begin);
            }
            if (begin != null && end != null && begin.getDate() != end.getDate()) 
                txt += " - ";
            if (end != null && (begin == null || begin.getDate() != end.getDate())) {
                txt += formatDateString(entry.time.end);
            }
        }
        if (entry.summary != null) 
            txt += "<br />" + entry.summary;
        txt += "</td>";
    } 
    catch (e) {
        alert("showMessage: " + e);
    }
    txt += "</tr>";
    return txt;
}
